(function($){
    ujs.define('debug', 'ujs.util', {
        log : function(msg, type){
            if(!type){
                type = 'log';
            }
            if(Type.isObject(msg)){
                msg = JSON.stringify(msg);
            }
            localStorage.setItem('debug_{0}_{1}'.format(type, Date.now()), msg);
            return this;
        },
        error : function(e){
            return this.log(e, 'error');
        },
        warn : function(e){
            return this.log(e, 'warn');
        },
        /**
         * 清除所有日志. 
         */
        clearLogs : function(key){
            var storage = window.localStorage;
            if(!key){  
                for (var i=storage.length - 1; i>-1; i--){     
                    key = storage.key(i);     
                    if(key.startsWith('debug_')){
                        storage.removeItem(key);                       
                    }
                }    
            } else {
                storage.removeItem(key);
            }        
        },
        /**
         * 按时间倒序获取日志. 
         */
        getLogs : function(){
            var storage = window.localStorage,
                logs = []; 
            for (var i=0, len=storage.length; i<len; i++){     
                var key = storage.key(i);     
                if(key.startsWith('debug_')){
                    var value = JSON.parse(storage.getItem(key)),
                        time = parseInt(key.split('_').last());
                    value['tick'] = time;    
                    value['time'] = (new Date(time)).format('yyyy-MM-dd hh:mm:ss');
                    if(Type.isObject(value['attach'])){
                        value['attach'] = JSON.stringify(value['attach']);
                    }
                    logs.push(value);
                }
            }      
            logs.sort(function(a, b){
                return (a.tick + '') < (b.tick + '');
            });      
            return logs;
        },
        /**
         * 将日志显示到控制台上.
         */
        showLogs : function(){
            var logs = this.getLogs();
            console.table(logs, ['time', 'tick', 'msg', 'code', 'lineNo', 'colNo', 'url', 'attach']);
        }
    });
})($);